const router = require( 'koa-router' )();
const path = require( 'path' );
const fs = require( 'fs' );
const DateMath = require('date-arithmetic');

const akUtil = require( '../utils/ak_utils' );
const redisUtil = require( '../utils/redis_utils' )

const userTable = require( '../models/user' );
const userPlanTable = require( '../models/user_plan' );
const apiKeyTable = require( '../models/api_key' );
const planTable = require( '../models/plan' );
const accountConfirmTable = require( '../models/account_confirm' );
const orderResetpwdTable = require( '../models/order_resetpwd' );
const userConsumeTable = require('../models/user_consume');
const config = require( '../config' );

const headers = { 'Content-Type': 'application/json', 'Encoding': 'utf8' };


const confirm = async function ( ctx, next ) {
    let key = ctx.params.key;
    let email = ctx.query.email;

    let status = 'invalid';

    if ( !key || !email ) {
        status = 'invalid';
    } else {
        let confirm = await accountConfirmTable.getByKey( key );
        if ( !confirm || confirm.length === 0 || confirm[ 0 ].confirmed ) {
            status = 'invalid';
        } else {

            let userId = confirm[ 0 ].userId;
            let result = await userTable.getUser( userId );
            let user = result[ 0 ];

            if ( email !== user.email ) {

                status = 'invalid';

            } else {

                try {

                    await userTable.updateConfirmed( userId, true );

                    await accountConfirmTable.updateConfirmed( key, true );

                    // add user consume

                    let result = await userConsumeTable.getByUserId(userId);

                    // 如果没有user consume记录，则新建一条记录

                    console.log('consume: ', result);

                    if(!result){

                        let startAt = user.created_at;
                        let endAt = DateMath.add(startAt, 1, 'month');

                        console.log(startAt, endAt);

                        await userConsumeTable.create(userId, 'free', 0, 0, 0, startAt, endAt);

                    }

                    status = 'valid';

                } catch ( e ) {

                    status = 'fail';

                }
            }

        }

        return ctx.render( 'confirm', {
            status,
            email,
            page: JSON.stringify(config.page)
        } );

    }
}

const resetPwd = async function ( ctx, next ) {
    let key = ctx.query.key;
    let email = ctx.query.email;

    let order = await orderResetpwdTable.getTodoOrder( email, key );
    if ( !order || order.length == 0 ) {
        let result = await userTable.getUserByEmail( email );
        let user = result[ 0 ];
    }
}

const getProfile = async function ( ctx, next ) {

    let userId = ctx.request.cookies.userId;

    let rows = await userTable.getUser( userId );

    if ( rows && rows.length > 0 ) {

        let result = rows[ 0 ];

        delete result.hash_password;
        delete result.salt;

        let plan = await userPlanTable.getCurrentPlan( userId );

        if ( plan && plan.length > 0 ) {
            let data = plan[ 0 ];

            result.plan = {
                name: data.plan,
                startAt: data.start_at,
                endAt: data.end_at
            }

        } else {
            result.plan = { name: 'free' };
        }

        ctx.body = { code: 0, data: result };

    } else {

        ctx.body = { code: 1, msg: '查询profile出错' };

    }

}

const getAK = async function ( ctx, next ) {

    let userId = ctx.request.cookies.userId;

    let rows = await apiKeyTable.getByUser( userId );

    if ( rows ) {

        ctx.body = { code: 0, data: rows };

    } else {

        ctx.body = { code: 1, msg: '查询ak出错' };
    }
}

const addAK = async function ( ctx, next ) {

    let userId = ctx.request.cookies.userId;
    let trust = ctx.request.body.trust || '';
    let type = ctx.request.body.type || 'browser';
    let key = akUtil.generateKey();

    trust.replace( /\s+/g, '' );

    let ak = {
        userId,
        key,
        type,
        trust,
        createdBy: 1
    }

    let result = await apiKeyTable.insert( ak );

    if ( result ) {

        ctx.body = { code: 0, ak };

    } else {

        ctx.body = { code: 1, msg: '添加ak出错' };

    }

}

const updateAK = async function ( ctx, next ) {

    let key = ctx.params.key;
    let trust = ctx.request.body.trust || '';
    trust.replace( /\s+/g, '' );

    if ( !key ) {
        ctx.body = { code: 1, msg: '缺少参数' };
        return;
    }

    let result = await apiKeyTable.setTrust( key, trust );

    if ( result ) {

        ctx.body = { code: 0 };
        return await redisUtil.del( `cache.ak.${ key }` );

    } else {

        ctx.body = { code: 1, msg: '更新ak出错' };

    }

}

const removeAK = async function ( ctx, next ) {

    let key = ctx.params.key;

    if ( !key ) {
        ctx.body = { code: 1, msg: '缺少参数' };
        return;
    }

    let result = await apiKeyTable.remove( key );

    if ( result ) {

        ctx.body = { code: 0 };
        return await redisUtil.del( `cache.ak.${ key }` );

    } else {

        ctx.body = { code: 1, msg: '删除ak出错' };

    }


}

router.get( '/confirm/:key', confirm );
router.get( '/reset', resetPwd );

router.get( '/profile', getProfile );

router.get( '/ak', getAK );
router.post( '/ak', addAK );
router.put( '/ak/:key', updateAK );
router.delete( '/ak/:key', removeAK );

module.exports = router;
